<template>
    <el-card class="box-card">
        <template #header>
            <div class="flex justify-between items-center px-3 box-border">
                <span>添加</span>
                <div>
                    <el-button type="info" size="small">取消</el-button>
                    <el-button type="danger" size="small" @click="createshuoshuo">确定</el-button>
                </div>
            </div>
        </template>
        <el-form :model="form" label-width="80px" class="frame">
            <el-form-item label="内容:">
                <el-input v-model="form.content" type="textarea" rows="4" placeholder="说说内容" resize="none" maxlength="60"
                    show-word-limit />
            </el-form-item>
            <el-form-item label="图片:" class="img-form">
                <upload :limit="9" :multiple="true" :height="100" :width="100" v-model:imglist="form.fileList"></upload>
            </el-form-item>
            <el-form-item label="置顶:">
                <el-switch v-model="form.istop" inline-prompt active-text="是" inactive-text="否" @change="changetop"/>
            </el-form-item>
            <el-form-item label="选择封面:">
                <el-button type="success" size="small" @click="changecover">选择封面</el-button>
            </el-form-item>

        </el-form>
        <dialogg :istoshow="showdialog" title="选择封面" @cansol="cansol" width="32%">
            <template #body>
                <div v-for="(item, index) in form.fileList" class="inline-block mr-1">
                    <el-checkbox v-model="item.iscover" size="small" @change="selectcover(item)"
                        :disabled="item.disabled" />
                    <el-image style="width: 100px; height: 100px ; margin:5px; border: 1px solid #eee ;vertical-align: top;"
                        :src="item.url" fit="cover" />
                </div>
            </template>
            <template #footer>
                <el-button @click="cansol">取消</el-button>
                <el-button type="primary" @click="subandclose">
                    确定
                </el-button>
            </template>
        </dialogg>
    </el-card>
</template>
<script setup>
import { ref, reactive, watch, onMounted,inject } from "vue"
import upload from "@/components/upload.vue"
import dialogg from "@/components/dialog.vue"
import { useBaseStore } from "@/store/Base.js"
import { Userstore } from "@/store/User.js"
import { getQiniuToken } from "@/api/users.js"
import { uploadqiniu, randomString } from "@/util/index.js"
import { useRoute,useRouter} from "vue-router"

import {
    addshuoshuo,
    uploadshuoshuoimg,
    apigetshuoshuoByid,
    editshuoshuo,
    updatashuoshuoimg,
    updatacover,
    cantop
} from "@/api/shuoshuo.js"
let reload = inject('reload')
const route = useRoute()
const router = useRouter()
let baseStore = useBaseStore()
let userstore = Userstore()
/* 是封面的标志 */
let coverflag = ""
/* 控制dialog的变量 */
let showdialog = ref(false)
/* 是否选取封面 */
let fleg = ref(false);
/* 说说的数据结构 */
const form = reactive({
    content: '',
    istop: false,
    fileList: [],
    corver: ""
})
/* 判断当前是添加还是编辑 */
let isadd = ref(true)
/* 检测有新的图片添加，就给这个图片添加属性 */
watch(() => form.fileList, (newval, oldval) => {
    if (newval.length > oldval.length) {
        if(isadd.value){
            fleg.value = false
        }
        setimgcoverAttrabuilt()
    }
})
/* 分存参数 */
function diliver(data) {
    form.content = data.shuoshuo_content
    form.istop = data.shuoshuo_istop
    form.corver = data.shuoshuo_cover
    coverflag = data.shuoshuo_cover.split("-")[1]
    fleg.value = true
    form.fileList = data.shuoshuoimgs_name.map(item => {
        return {
            url: item.shuoshuo_url,
            id: item.shuoshuo_id
        }
    })
    let re = new RegExp(coverflag, 'g');
    form.fileList.forEach(item => {
        if (re.test(item.url)) {
            item.iscover = true
            item.disabled = false
        }
    })

}
onMounted(async () => {
    if (route.query?.id) {
        isadd.value = false
        let data = await apigetshuoshuoByid(route.query.id)
        if (data.data.status == 200) {
            let shuoshuo = data.data.data
            diliver(shuoshuo)
        }
    }
})
/* 提交表单 */
async function createshuoshuo() {
    if (checkform()) {
        /* 参数校验通过 */
        /* 参数校验通过 获取七牛云的token */
        let data = await getQiniuToken();
        /* 获取七牛云的token成功 */
        if (data.data.status == 200) {
            baseStore.qiniuToken = data.data.data.uploadToken;
            /* 查看是否选取封面 */
            if (!fleg.value) {
                fleg.value = true;
                opendialoginit();
            }
            if (isadd.value) {
                let ress = await uploadqiniu(form.fileList,coverflag);
                /* 正则匹配 包含 corver- 的图片就是封面 */
                let re = new RegExp(coverflag, 'g');
                let files_name = ress.map((item) => {
                    if (re.test(item.data?.key)) {
                        form.corver = import.meta.env.VITE_API_PHOTO + item.data?.key;
                        console.log(form.corver);
                    }
                    return import.meta.env.VITE_API_PHOTO + item.data?.key
                })
                let pramas = integratPrams()
                let res = await addshuoshuo(pramas)
                if (res.data.status == 200) {
                    let shuoshuo_id = res.data.data.shuoshuo_id
                    let ress = await uploadshuoshuoimg({ shuoshuo_id, shuoshuo_imglist: files_name })
                    if (ress.data.status == 200) {
                        ElMessage({
                            message: res.data.message,
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: res.data.message,
                            type: 'error',
                        })
                    }
                    reset()
                } else {
                    ElMessage({
                        message: res.data.message,
                        type: 'error',
                    })
                    reset()
                }
            } else {
                let isfit=false/* 查看当前设置的封面是 新添加的还是 在原来的图片加入的 */
                let ress = await uploadqiniu(form.fileList, coverflag);
                /* 正则匹配 包含 corver- 的图片就是封面 */
                let re = new RegExp(coverflag, 'g');
                let files_name = ress.map((item) => {
                    if (re.test(item.data?.key)) {
                        isfit=true
                        form.corver = import.meta.env.VITE_API_PHOTO + item.data?.key;
                    }
                    return import.meta.env.VITE_API_PHOTO + item.data?.key
                })
                /* 如果是在原来图片上的 */
                if(!isfit){
                    /* 先找到是哪张图片是选择的封面 */
                    let newpicname = ""
                    let oldpicname = ""
                    form.fileList.forEach((item,index)=>{
                        if(item.iscover){
                            oldpicname = item.url.split("/").pop()
                            newpicname =`-${coverflag}-`+item.url.split("/").pop()
                            item.url = item.url.replace(item.url.split("/").pop(),newpicname)
                        }
                    })
                    form.corver = import.meta.env.VITE_API_PHOTO + newpicname;
                    /* 替换原来的图片 shuoshuo_id,shuoshuo_cover,oldshuoshuocover*/
                    let res = await updatacover({shuoshuo_id:route.query.id,shuoshuo_cover:newpicname,oldshuoshuocover:oldpicname})
                }
                let pramas = integratPrams()
                let res = await editshuoshuo(pramas)
                if (res.data.status == 200) {
                    let shuoshuo_id = res.data.data.shuoshuo_id
                    let fileList = []
                    for (let i = 0; i < form.fileList.length; i++) {
                        const el = form.fileList[i];
                        if (!el.raw) {
                            fileList.push(el.url)
                        }
                        continue;
                    }
                    let shuoshuo_imglist = files_name.concat(fileList)
                    let ress = await updatashuoshuoimg({ shuoshuo_id, shuoshuo_imglist })
                    if(ress.data.status == 200){
                        ElMessage({
                            message: "修改成功",
                            type: 'success',
                        })
                        reset()
                        router.push({ path: '/shuoshuo' })
                    }
                }else{
                    reload()
                }
            }
        }
    } else {
        ElMessage({
            message: "参数错误哦",
            type: 'error',
        })
    }
}
/* 切换是否置顶 */
async function changetop(val){
    if(val){
        /* 校验能否置顶 */
        let res =await cantop()
        
        if(res.data.status!== 200){
            ElMessage({
                message: "置顶失败,最多置顶一个",
                type: 'error',
            })
            form.istop = false
        }
    }
}
/* 重制参数*/
function reset() {
    coverflag=""
    form.content = ''
    form.istop = false
    form.fileList = []
    form.corver = ''
    fleg.value = false
    showdialog.value = false
}
/* 校验参数 */
function checkform() {
    if (!form.content) {
        console.log("请输入内容");
        return false;
    }
    if (!form.fileList?.length) {
        console.log("请添加图片");
        return false;
    }

    return true;
}
/* 整合参数*/
function integratPrams() {
    return isadd.value ? {
        shuoshuo_author: userstore.userInfo.username,
        shuoshuo_authorid: userstore.userInfo.id,
        shuoshuo_istop: form.istop,
        shuoshuo_content: form.content,
        shuoshuo_status: 1,
        shuoshuo_cover: form.corver,
    } : {
        shuoshuo_author: userstore.userInfo.username,
        shuoshuo_authorid: userstore.userInfo.id,
        shuoshuo_istop: form.istop,
        shuoshuo_content: form.content,
        shuoshuo_status: 1,
        shuoshuo_cover: form.corver,
        shuoshuo_id: route.query.id,
    }
}
/* 添加为图片属性 */
function setimgcoverAttrabuilt() {
    form.fileList = form.fileList.map((item) => {
        if (item.hasOwnProperty('iscover') && item.hasOwnProperty('disabled')) {
            return item
        } else {
            return Object.assign(item, { iscover: false, disabled: true })
        }

    })
}
/* 打开dialog选取封面 */
function changecover() {
    console.log(fleg.value);
    if (!form.fileList?.length) {
        console.log("请添加图片");
    } else {
        if (!fleg.value) {
            /* 第一次打开选取封面 */
            opendialoginit();
            fleg.value = true
            showdialog.value = true;
        } else {
            /* 第二次打开选取封面 */
            showdialog.value = true;
        }
    }
}
/* 选择图片完成 */
function subandclose() {
    showdialog.value = false;
}
/* 初始化 取消选取封面 的时候就默认选取第一张当作图片 */
function opendialoginit() {
    coverflag = randomString(6)
    form.fileList[0].iscover = true;
    form.fileList[0].disabled = false;
    for (let i = 1; i < form.fileList.length; i++) {
        form.fileList[i].disabled = true;
        form.fileList[i].iscover = false;
    }
}
/* 选择封面图片 */
function selectcover(item) {
    form.fileList.forEach((data) => {
        if (data.url == item.url) {
            data.iscover != data.iscover;
            coverflag = randomString(6)
        } else {
            if (fleg.value) {
                data.disabled = false;
            } else {
                data.disabled = true;
            }

        }
    })
    fleg.value = !fleg.value;
}
/* 取消选择图片 */
function cansol() {
    showdialog.value = false;
}
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 5px 10px !important;
}

:deep(.el-card__body) {
    padding: 20px 30px !important;
}

:deep(.el-dialog__body) {
    display: flex !important;

}

.frame {

    .el-form-item {
        .el-input {
            width: 220px;
        }

        .el-select {
            width: 220px;
        }

        .el-form-item__content {
            .el-textarea {
                width: 220px;
            }
        }
    }
}

.img-form {
    :deep(.el-form-item__content) {
        width: 370px !important;
        height: 370px !important;
        max-width: 330px !important;
        max-height: 330px !important;
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        flex-wrap: wrap;
    }
}
</style>